<template>
  <div class="health-check-form">
    <div class="form-container">
      <h2>从业人员健康体检预约</h2>
      <!-- 标签页 -->
      <el-tabs
          v-model="activeName"
          type="card"
          class="demo-tabs"
          @tab-click="handleClick"
      >
        <!--个人预约标签-->
        <el-tab-pane label="个人预约" name="first" :disabled="isPerDisabled">
          <el-form class="form-con" ref="perReserveFormRef" :model="perReserveForm" label-width="120px" :rules="rules"
                   size="large">
            <el-row :gutter="20">
              <el-col :span="15">
                <el-form-item label="身份证号码:" prop="idCard" style="position:relative;">
                  <el-input v-model="perReserveForm.idCard" placeholder="请输入身份证号码" @input="handleIdCardInput"></el-input>
                </el-form-item>
              </el-col>

              <el-col>
                <el-button style="position: absolute;left: 744px;top: 0;" type="warning" @click="checkIdCard">信息核验
                </el-button>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="15">
                <el-form-item label="姓名:" prop="name">
                  <el-input v-model="perReserveForm.name" placeholder="请输入姓名"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="15">
                <el-form-item label="电话:" prop="phone">
                  <el-input v-model="perReserveForm.phone" placeholder="请输入电话"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="15">
                <el-form-item label="预约医院:" prop="reserveHospital">
                  <!--                  <el-input v-model="perReserveForm.reserveHospital" placeholder="请选择预约医院"></el-input>-->
                  <el-select :disabled="!isInfoChecked" v-model="perReserveForm.reserveHospital" filterable
                             placeholder="请选择预约医院"
                             @change="handlePerHospitalChange">
                    <el-option
                        v-for="item in reserveHospitals"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                  <span style="color:#9b9b9b;">地址：{{ perReserveForm.reserveHospitalAddress }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-left: 0;">
              <el-form-item label="预约日期:" prop="reserveDate">
                <el-date-picker
                    v-model="perReserveForm.reserveDate"
                    type="date"
                    placeholder="请选择日期"
                    size="large"
                    value-format="YYYY-MM-DD"
                    :disabled-date="disabledDate"
                />
              </el-form-item>

              <el-form-item label="预约时间:" prop="reserveDate">
                <el-select :disabled="!isHospitalChecked" v-model="perReserveForm.reserveHour"
                           placeholder="请选择时间" size="large" style="width: 240px;margin-left: 10px;">
                  <el-option
                      v-for="item in reserveHours"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-row>

            <el-row>
              <div class="legal-notice">
                <p style="font-size: 16px;"><span style="color: red;">注意：</span><span style="color: gray;">点击信息核验是为了核验用户的身份信息。姓名和电话自动回填，若弹出信息核验失败，请登录甘肃政务服务网兰州新区子站进行健康证申报。</span>
                </p>
              </div>
            </el-row>
            <div class="form-actions">
              <el-button size="large" type="danger" @click="personEnsure">确认预约</el-button>
              <el-button size="large" @click="goBack">返回</el-button>
            </div>
          </el-form>
        </el-tab-pane>

        <!--单位预约标签-->
        <el-tab-pane label="单位预约" name="second" :disabled="isUnitDisabled">
          <el-form class="form-con" ref="unitReserveFormRef" :model="unitReserveForm" label-width="120px" :rules="rule"
                   size="large">
            <el-row :gutter="20">
              <el-col :span="15">
                <el-form-item label="组织机构代码:" prop="socialCreditCode" style="position:relative;">
                  <el-input v-model="unitReserveForm.socialCreditCode" placeholder="请输入组织机构代码"></el-input>
                </el-form-item>
              </el-col>

              <el-col>
                <el-button style="position: absolute;left: 744px;top: 0;" type="warning" @click="checkSocialCreditCode">
                  信息核验
                </el-button>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="15">
                <el-form-item label="企业名称:" prop="unitName">
                  <el-input v-model="unitReserveForm.unitName" placeholder="请输入企业名称"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="15">
                <el-form-item label="预约人数:" prop="phone">
                  <!-- 体检人员下拉选择 -->
                  <el-select v-model="unitReserveForm.reservePersons" placeholder="请选择参加体检的人" multiple
                             value-key="idCard">
                    <!-- 表头 -->
                    <el-option
                        :value="null"
                        disabled style="font-weight: bold; background-color: #f5f7fa;">
                      <span style="display: flex; justify-content: space-around;text-align: center;">
                        <span>姓名</span>
                        <span>身份证号码</span>
                        <span>电话</span>
                      </span>
                    </el-option>

                    <!-- 数据项 -->
                    <el-option
                        v-for="item in reservePersons"
                        :label="item.name"
                        :value="item"
                        :key="selectKey">
                      <span style="display: flex; justify-content: space-around;text-align: center;">
                        <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ item.name }}</span>
                        <span>&nbsp;&nbsp;&nbsp;&nbsp;{{ item.idCard }}</span>
                        <span>{{ item.phone }}</span>
                      </span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="15">
                <el-form-item label="预约医院:" prop="reserveHospital">
                  <el-select :disabled="!isUnitInfoChecked" v-model="unitReserveForm.reserveHospital" filterable
                             placeholder="请选择预约医院"
                             @change="handleUnitHospitalChange">
                    <el-option
                        v-for="item in reserveHospitals"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                  <span style="color:#9b9b9b;">地址：{{ unitReserveForm.reserveHospitalAddress }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-left: 0;">
              <el-form-item label="预约日期:" prop="reserveDate">
                <el-date-picker
                    v-model="unitReserveForm.reserveDate"
                    type="date"
                    placeholder="请选择日期"
                    size="large"
                    value-format="YYYY-MM-DD"
                />
              </el-form-item>

              <el-form-item label="预约时间:" prop="reserveDate">
                <el-select :disabled="!isHospitalChecked" v-model="unitReserveForm.reserveHour"
                           placeholder="请选择时间" size="large" style="width: 240px;margin-left: 10px;">
                  <el-option
                      v-for="item in reserveHours"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-row>

            <el-row>
              <div class="legal-notice">
                <p style="font-size: 16px;"><span style="color: red;">注意：</span><span style="color: gray;">点击信息核验是为了核验企业信息。企业名称自动回填，若弹出信息核验失败，请登录甘肃政务服务网兰州新区子站进行健康证申报。</span>
                </p>
              </div>
            </el-row>
            <div class="form-actions">
              <el-button size="large" type="danger" @click="unitEnsure">确认预约</el-button>
              <el-button size="large" @click="goBack">返回</el-button>
            </div>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script lang="js" setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {
  getCookie,
  loadAllHospitalAddress,
  loadReserveHospital,
  reserveHospitalAddress,
  reserveHospitals,
  reserveHours,
  rules
} from "@/api/employee/applyBaseData.js";
import {addPersonReserve, addUnitReserve, checkReserveInfo, checkUnitReserveInfo} from "@/api/employee/reserve";
import {useRoute} from 'vue-router';
import {debounce} from "lodash-es";
import useUserStore from "@/store/modules/user.js";
import {getHolidays, getWorkdays} from "@/api/system/holiday.js";

const userStore = useUserStore()
const {proxy} = getCurrentInstance()
// tab标签页
const activeName = ref('first')
// 个人预约表单校验
const perReserveFormRef = ref(null)
// 单位预约表单校验
const unitReserveFormRef = ref(null)
// 是否核验信息
const isInfoChecked = ref(false)
const isUnitInfoChecked = ref(false)
// 是否选择预约医院
const isHospitalChecked = ref(false)
// 新增 key 控制企业人员下拉框刷新
const selectKey = ref(0)
const isIdCardDisabled = ref(false); // 身份证输入框是否禁用 设置为 true 表示不可输入
const isPerDisabled = ref(false); // 个人申报tab是否禁用 设置为 true 表示不可输入
const isUnitDisabled = ref(false); // 企业申报tab是否禁用 设置为 true 表示不可输入


// 定义企业的预约人员
let reservePersons = ref([
  // {name: '张三', idCard: '350123199506164477', phone: '13812345678'},
  // {name: '李四', idCard: '140427199307248902', phone: '15162345678'}
])

const route = useRoute();
// 个人预约表单信息
const perReserveForm = ref({
  idCard: '',
  name: '',
  phone: '',
  // 预约医院
  reserveHospital: null,
  //  预约日期
  reserveDate: '',
  //  预约时间
  reserveHour: '8:30-11:30',
  reserveHospitalAddress: '',
})

// 单位预约表单信息
const unitReserveForm = ref({
  socialCreditCode: '',
  unitName: '',
  isUnit: 1,
  //预约的人员
  reservePersons: [],
  reserveHospital: null,
  //  预约日期
  reserveDate: '',
  //  预约时间
  reserveHour: '8:30-11:30',
  reserveHospitalAddress: '',
})

// 清空个人预约表单
const resetPersonForm = () => {
  perReserveForm.value = {
    idCard: '',
    name: '',
    phone: '',
    reserveHospital: null,
    reserveDate: '',
    reserveHour: '8:30-11:30',
  };
  isInfoChecked.value = false;
  perReserveFormRef.value?.clearValidate();
};

// 清空单位预约表单
const resetUnitForm = () => {
  unitReserveForm.value = {
    socialCreditCode: '',
    unitName: '',
    isUnit: 1,
    //预约的人员
    reservePersons: [],
    reserveHospital: null,
    //  预约日期
    reserveDate: '',
    //  预约时间
    reserveHour: '8:30-11:30',
  };
  isInfoChecked.value = false;
  unitReserveFormRef.value?.clearValidate();
};

/*个人信息核验*/
function checkIdCard() {
  perReserveFormRef.value.validateField('idCard', (valid) => {
    if (valid) {
      const data = perReserveForm.value.idCard
      // 校验身份证是否申报过
      checkReserveInfo(data).then(response => {
        if (response.data && response.data.auditStatus === 1) {
          if (response.data.isReserve === 0) {
            perReserveForm.value.name = response.data.name
            perReserveForm.value.phone = response.data.phone

            // 检验成功加载相应的医院
            loadReserveHospital(response.data.parkId);
            isInfoChecked.value = true
            // TODO 加载完医院加载医院相应的预约时间

            ElMessage.success('信息核验成功！');
          } else if (response.data.tjStatus === 0) {
            proxy.$alert(
                "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;font-size: 18px;color: red;line-height: 35px;text-align: center;'>" +
                "<span>您已预约体检，请勿重复预约。预约日期：" + response.data.reserveDate + "</span>" +
                "</div>",
                "核验结果",
                {dangerouslyUseHTMLString: true}
            );
            resetPersonForm();
          } else if (response.data.tjStatus === 1) {
            proxy.$alert(
                "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;font-size: 18px;color: red;line-height: 35px;text-align: center;'>" +
                "<span>您的体检正在进行中，无法重复预约</span>" +
                "</div>",
                "核验结果",
                {dangerouslyUseHTMLString: true}
            );
            resetPersonForm();
          } else if (response.data.tjStatus === 2) {
            proxy.$alert(
                "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;font-size: 18px;color: red;line-height: 35px;text-align: center;'>" +
                "<span>您最近一次体检日期：" + response.data.reserveDate + "，结果：" + (response.data.qualify === 1 ? '合格' : '不合格') + "</span>" +
                "</div>",
                "核验结果",
                {dangerouslyUseHTMLString: true}
            )
            resetPersonForm();
          } else if (response.data.tjStatus === 3) {
            proxy.$alert(
                "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;font-size: 18px;color: red;line-height: 35px;text-align: center;'>" +
                "<span>您的体检预约：" + response.data.reserveDate + "已过期，请重新预约</span>" +
                "</div>",
                "核验结果",
                {dangerouslyUseHTMLString: true}
            )
            resetPersonForm();
          }

        } else if (response.data && response.data.auditStatus !== 1) {
          resetPersonForm()
          proxy.$alert(
              "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;font-size: 18px;color: red;line-height: 35px;text-align: center;'>" +
              "<span>信息核验失败，您当前审核状态为：" + (response.data.auditStatus === 0 ? '待审核' : response.data.auditStatus === 2 ? '审核未通过' : '信息核验失败，若您还未申报，请登录甘肃政务服务网兰州新区子站进行申报，等审核成功短信通知后进行预约！') + "</span>" +
              "</div>",
              "核验结果",
              {dangerouslyUseHTMLString: true}
          )
        } else {
          proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;font-size: 18px;color: red;line-height: 35px;text-align: center;'><span>信息核验失败，若您还未申报，请登录甘肃政务服务网兰州新区子站进行申报，等审核成功短信通知后进行预约！</span></div>", "核验结果", {dangerouslyUseHTMLString: true})
          resetPersonForm()
        }
      })

    }
  });
}

/*单位信息校验*/
function checkSocialCreditCode() {
  unitReserveFormRef.value.validateField('socialCreditCode', (valid) => {
    if (valid) {
      const data = unitReserveForm.value.socialCreditCode
      // 校验机构代码是否申报过
      checkUnitReserveInfo(data).then(response => {
        if (response.data) {
          // 给企业预约的表单赋值
          unitReserveForm.value.unitName = response.data.unitName
          // 检验成功加载相应的体检人员
          reservePersons.value = response.data.reservePersons
          selectKey.value++ // 刷新 el-select
          // 检验成功加载相应的医院
          loadReserveHospital(response.data.parkId);
          isUnitInfoChecked.value = true
          // TODO 加载完医院加载医院相应的预约时间

          ElMessage.success('信息核验成功！');
        } else {
          resetUnitForm()
          proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;font-size: 18px;color: red;line-height: 35px;text-align: center;'><span>信息核验失败，此单位未含审核通过的人员；若您的单位还未申报，请登录甘肃政务服务网兰州新区子站进行申报，等审核成功短信通知后进行预约！</span></div>", "核验结果", {dangerouslyUseHTMLString: true})
        }
      })

    }
  });
}


// 检查是否为周末
const isWeekend = (date) => {
  const dayOfWeek = date.getDay();
  return dayOfWeek === 0 || dayOfWeek === 6;
}

// 检查日期是否可以预约
const isValidReserveDate = (date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  // 获取当前时间
  const now = new Date();
  // 设置11:30的时间点
  const cutoffTime = new Date();
  cutoffTime.setHours(11, 30, 0, 0);

  // 如果当前时间已经超过11:30
  if (now > cutoffTime) {
    // 预约日期必须大于今天
    if (date <= today) {
      return {valid: false, message: '当前时间已过11:30，只能选择明天及以后的日期！'};
    }
  } else {
    // 如果未到11:30，预约日期不能早于今天
    if (date < today) {
      return {valid: false, message: '预约时间不能早于今天！'};
    }
  }
  return {valid: true};
}

// 节假日
let holidays = ref([])
// 节假日补班
let workDays = ref([])
// 禁用日期
function disabledDate(date) {
  // 获取当前月份
  const month = date.getMonth() + 1; // getMonth() 返回 0-11，所以需要 +1
  // 获取当前日期
  const day = date.getDate();

  // 获取当前时间
  const now = new Date();
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  // 禁用今天之前的日期
  if (date < today) {
    return true;
  }

  // 使用本地时间格式化为 YYYY-MM-DD
  const year = date.getFullYear();
  const dateString = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  // 禁用法定节假日期
  const holiday = holidays.value.includes(dateString);
  if (holiday) {
    return true;
  }
  // 放开法定节假日调班
  const workDay = workDays.value.includes(dateString);
  if (workDay) {
    return false;
  }

  // 禁用周末
  if (isWeekend(date)) {
    return true;
  }
}

// 防抖（600ms 内重复点击不会触发）
const personEnsure = debounce(rawPersonEnsure, 600)

// 个人确认预约
function rawPersonEnsure() {
  proxy.$refs["perReserveFormRef"].validate(valid => {
    if (valid) {
      const reserveDate = new Date(perReserveForm.value.reserveDate);
      reserveDate.setHours(0, 0, 0, 0);
      const dateValidation = isValidReserveDate(reserveDate);
      // 校验日期
      if (dateValidation.valid) {
        addPersonReserve(perReserveForm.value).then(response => {
          if (response.code === 200 && response.data >= 1) {
            resetPersonForm(); // 重置表单数据
            ElMessage.success('预约成功！');
          } else {
            ElMessage.error('预约失败:' + response.msg)
          }
        })
        // 预约成功后重置确认状态
        isInfoChecked.value = false
      } else {
        ElMessage.error(dateValidation.message);
      }
    }
  })
}

// 防抖（600ms 内重复点击不会触发）
const unitEnsure = debounce(rawUnitEnsure, 600)

// 企业确认预约
function rawUnitEnsure() {
  proxy.$refs["unitReserveFormRef"].validate(valid => {
    if (valid) {
      const reserveDate = new Date(unitReserveForm.value.reserveDate);
      reserveDate.setHours(0, 0, 0, 0);
      const dateValidation = isValidReserveDate(reserveDate);
      // 校验日期
      if (dateValidation.valid) {
        addUnitReserve(unitReserveForm.value).then(response => {
          if (response.code === 200 && response.data >= 1) {
            resetUnitForm(); // 重置表单数据
            ElMessage.success('预约成功！');
          }
        })
        // 预约成功后重置确认状态
        isInfoChecked.value = false
      } else {
        ElMessage.error(dateValidation.message);
      }
    }
  })
}

/*
个人预约医院改变事件
 */
function handlePerHospitalChange(selectedValue) {
  // 从 reserveHospitals 中找到选中的医院对象
  const selectedHospital = reserveHospitalAddress.value.find(item => item.value === selectedValue);
  if (selectedHospital) {
    // 将医院地址赋值给表单字段
    perReserveForm.value.reserveHospitalAddress = selectedHospital.label || '';
  } else {
    perReserveForm.value.reserveHospitalAddress = '';
  }
}

function handleIdCardInput(value) {
  // 将输入的字母 x 转换为大写
  perReserveForm.value.idCard = value.replace(/x/g, 'X');
}

/*
单位预约医院改变事件
 */
function handleUnitHospitalChange(selectedValue) {
  // 从 reserveHospitals 中找到选中的医院对象
  const selectedHospital = reserveHospitalAddress.value.find(item => item.value === selectedValue);
  if (selectedHospital) {
    // 将医院地址赋值给表单字段
    unitReserveForm.value.reserveHospitalAddress = selectedHospital.label || '';
  } else {
    unitReserveForm.value.reserveHospitalAddress = '';
  }
}

const rule = reactive({
  unitName: [
    {required: true, message: '请输入企业名称', trigger: 'blur'}
  ],
  socialCreditCode: [
    {required: true, message: '请输入机构代码', trigger: 'blur'}
  ],
  reserveHospital: [
    {required: true, message: '请选择预约医院', trigger: 'blur'}
  ],
  reserveDate: [
    {required: true, message: '请选择预约日期', trigger: 'blur'}
  ],
  reserveHour: [
    {required: true, message: '请选择预约时间', trigger: 'blur'}
  ]
})

/*返回按钮跳转*/
const goBack = () => {
  // 这里可以根据实际路由配置进行调整
  window.history.back()
}

onMounted(() => {
  // 判断登录用户是系统用户还是普通用户 normal
  userStore.getInfo().then((res) => {
    // 获取登录用户类型
    const userType = res.user.userType;
    // 获取唯一识别码
    const identifyCode = res.user.identifyCode;
    // 获取姓名
    const nickName = res.user.nickName;

    // 获取角色
    const roles = res.roles;
    const role = roles[0];

    // 如果用户为普通用户,那么就查询当前用户的数据
    if ('normal' === role) {
      if ("01" === userType) {
        // 如果是个人用户则跳转到个人预约
        activeName.value = 'first';
        isUnitDisabled.value = true;
        isIdCardDisabled.value = true;
        perReserveForm.value.idCard = identifyCode;
        perReserveForm.value.name = nickName;
      } else if ("02" === userType) {
        // 如果是企业用户则跳转到企业预约
        activeName.value = 'second';
        isPerDisabled.value = true;
        isIdCardDisabled.value = true;
        unitReserveForm.value.socialCreditCode = identifyCode;
        unitReserveForm.value.unitName = nickName;
      }
    }
  });
  // openNotice();
  loadAllHospitalAddress();

  // 获取当前年份
  const currentYear = new Date().getFullYear()
  // 查询所有节假日补班
  getWorkdays(currentYear).then(response => {
    workDays.value = response.data
  })
  // 查询所有节假日
  getHolidays(currentYear).then(response => {
    holidays.value = response.data
  })
})

// 页面加载前跳转单点登录
onBeforeMount(() => {
  // 判断cookie中是否存在token
  const adminToken = getCookie('Admin-Token');
  // 如果不存在,先登录
  if (!adminToken) {
    const env = import.meta.env.VITE_APP_ENV
    const redirect = encodeURIComponent('/employee/reserve')
    let backUrl
    if (env === 'development') {
      backUrl = encodeURIComponent(`http://127.0.0.1:18766/sso/perLogin?redirect=${redirect}`)
    } else if (env === 'production') {
      backUrl = encodeURIComponent(`http://117.157.64.139:9000/sso/perLogin?redirect=${redirect}`)
    }

    const loginUrl = `https://zwfw.gansu.gov.cn/gsjis/natural/login?appmark=lzxqcyryjktipt&backUrl=${backUrl}`
    window.location.href = loginUrl
  }
})
</script>

<style scoped>
.health-check-form {
  background-color: #f5f5f5;
  background-image: url('');
  min-height: 100vh;
  padding: 20px;
}

.form-container {
  background-color: white;
  padding: 30px;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-width: 1400px;
  margin: 0 auto;
}

h2 {
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.legal-notice {
  margin: 30px 0;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.legal-notice p {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 15px;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
}

.el-button + .el-button {
  margin-left: 20px;
}

.form-con {
  margin-top: 45px;
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.item {
  margin-top: 10px;
  margin-right: 30px;
}
</style>